#include "adminmanagement.h"
#include "ui_adminmanagement.h"
#include <QMessageBox>
#include <QDebug>

AdminManagement::AdminManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AdminManagement),
    m_userManager(nullptr)
{
    ui->setupUi(this);

    // 设置表头
    QStringList headers;
    headers << "用户名" << "密码" << "手机号" << "邮箱" << "昵称" << "角色";
    ui->tableWidget->setHorizontalHeaderLabels(headers);

    // 连接信号槽
    connect(ui->pushButton_add, &QPushButton::clicked, this, &AdminManagement::onAddUser);
    connect(ui->pushButton_edit, &QPushButton::clicked, this, &AdminManagement::onEditUser);
    connect(ui->pushButton_delete, &QPushButton::clicked, this, &AdminManagement::onDeleteUser);
}

AdminManagement::~AdminManagement()
{
    delete ui;
}

void AdminManagement::setUserManager(UserManager* manager)
{
    m_userManager = manager;
    refreshTable();
}

void AdminManagement::refreshTable()
{
    if (!m_userManager) return;

    QMutexLocker lock(&m_userManager->m_mutex); // 使用UserManager的锁

    ui->tableWidget->setRowCount(0);

    // 使用UserManager执行查询
    QString result = m_userManager->executeQuery("SELECT username, password, phone, email, nickname, role FROM users");

    if (result.startsWith("Error:")) {
        QMessageBox::warning(this, "错误", "获取用户列表失败: " + result);
        return;
    }

    // 解析结果
    QStringList lines = result.split('\n', QString::SkipEmptyParts);
    for (const QString &line : lines) {
        QStringList fields = line.split("|", QString::SkipEmptyParts);
        if (fields.size() < 6) continue;

        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);

        for (int i = 0; i < 6; ++i) {
            ui->tableWidget->setItem(row, i, new QTableWidgetItem(fields[i].trimmed()));
        }
    }
}

void AdminManagement::onAddUser()
{
    if (!m_userManager) return;

    QString username = ui->lineEdit_username->text().trimmed();
    QString password = ui->lineEdit_password->text();
    QString phone = ui->lineEdit_phone->text().trimmed();
    QString email = ui->lineEdit_email->text().trimmed();
    QString nickname = ui->lineEdit_nickname->text().trimmed();
    QString role = ui->comboBox_role->currentText();

    if (username.isEmpty() || password.isEmpty() || phone.isEmpty() || email.isEmpty()) {
        QMessageBox::warning(this, "警告", "请填写完整的用户信息");
        return;
    }

    std::pair<bool, UserManager::UserError> result = m_userManager->registerUser(username, password, email, phone, role, nickname);

    if (result.first) {
        QMessageBox::information(this, "成功", "用户添加成功");
        refreshTable();

        // 清空输入框
        ui->lineEdit_username->clear();
        ui->lineEdit_password->clear();
        ui->lineEdit_phone->clear();
        ui->lineEdit_email->clear();
        ui->lineEdit_nickname->clear();
    } else {
        QString errorMsg = "添加失败: ";
        switch (result.second) {
        case UserManager::UserError::UserExists:
            errorMsg += "用户名已存在"; break;
        case UserManager::UserError::WeakPassword:
            errorMsg += "密码强度不足"; break;
        default:
            errorMsg += "未知错误"; break;
        }
        QMessageBox::warning(this, "错误", errorMsg);
    }
}

void AdminManagement::onEditUser()
{
    if (!m_userManager) return;

    int row = ui->tableWidget->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "警告", "请先选择要修改的用户");
        return;
    }

    QString username = ui->tableWidget->item(row, 0)->text();
    QString newPassword = ui->lineEdit_password->text();
    QString newPhone = ui->lineEdit_phone->text().trimmed();
    QString newEmail = ui->lineEdit_email->text().trimmed();
    QString newNickname = ui->lineEdit_nickname->text().trimmed();
    QString newRole = ui->comboBox_role->currentText();

    if (newPassword.isEmpty() && newPhone.isEmpty() && newEmail.isEmpty() &&
        newNickname.isEmpty() && newRole == ui->comboBox_role->itemText(0)) {
        QMessageBox::warning(this, "警告", "没有修改任何信息");
        return;
    }

    // 构建更新SQL
    QStringList updates;
    if (!newPhone.isEmpty()) updates << QString("phone='%1'").arg(newPhone);
    if (!newEmail.isEmpty()) updates << QString("email='%1'").arg(newEmail);
    if (!newNickname.isEmpty()) updates << QString("nickname='%1'").arg(newNickname);
    updates << QString("role='%1'").arg(newRole);

    // 如果有新密码，使用UserManager的resetPassword方法
    if (!newPassword.isEmpty()) {
        // 假设使用邮箱或手机号作为验证信息
        QString verifyInfo = newEmail.isEmpty() ? newPhone : newEmail;

        auto result = m_userManager->resetPassword(username, verifyInfo, newPassword);
        if (!result.first) {
            QString errorMsg = "密码更新失败: ";
            switch (result.second) {
                case UserManager::UserError::UserNotFound:
                    errorMsg += "用户不存在"; break;
                case UserManager::UserError::WeakPassword:
                    errorMsg += "密码强度不足"; break;
                default:
                    errorMsg += "未知错误"; break;
            }
            QMessageBox::warning(this, "错误", errorMsg);
            return;
        }
    }

    // 更新其他信息
    if (!updates.isEmpty()) {
        QString sql = QString("UPDATE users SET %1 WHERE username='%2'")
                         .arg(updates.join(", "))
                         .arg(username);

        QString result = m_userManager->executeQuery(sql);
        if (result.startsWith("Error:")) {
            QMessageBox::warning(this, "错误", "更新失败: " + result);
            return;
        }
    }

    QMessageBox::information(this, "成功", "用户信息已更新");
    refreshTable();
}

void AdminManagement::onDeleteUser()
{
    if (!m_userManager) return;

    int row = ui->tableWidget->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "警告", "请先选择要删除的用户");
        return;
    }

    QString username = ui->tableWidget->item(row, 0)->text();

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认",
                                 QString("确定要删除用户 %1 吗?").arg(username),
                                 QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QString sql = QString("DELETE FROM users WHERE username='%1'").arg(username);
        QString result = m_userManager->executeQuery(sql);

        if (result.startsWith("Error:")) {
            QMessageBox::warning(this, "错误", "删除失败: " + result);
        } else {
            QMessageBox::information(this, "成功", "用户已删除");
            refreshTable();
        }
    }
}
